package cn.sunny360.core.handler.http;

import cn.sunny360.core.common.PhResult;
import cn.sunny360.core.service.GroupService;
import cn.sunny360.core.utils.Container;
import cn.sunny360.core.utils.JsonUtil;
import io.vertx.core.Promise;
import io.vertx.core.impl.logging.Logger;
import io.vertx.core.impl.logging.LoggerFactory;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.stream.Collectors;
/*
 * Copyright ©2021 su binglun(9085309@qq.com). All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *---------------------------------------------------------------------
 *-                                                                   -
 *-           Website : http://phoenix.sunny360.cn/                   -
 *-                                                                   -
 *---------------------------------------------------------------------
 */
public class GroupHandler extends HttpBaseHandler{
    private static Logger logger = LoggerFactory.getLogger(GroupHandler.class);
    private GroupService groupService;

    public GroupHandler() {
        groupService = Container.getComponent(GroupService.class);
    }

    public void createGroup(RoutingContext context) {
        JsonObject json = context.get("ext");
        String groupName = json.getString("groupName");
        Long createUserId = json.getLong("createUserId");
        JsonArray jsonArray = json.getJsonArray("memberList");
        List<Long> memberList = jsonArray.stream()
                .map(e -> new Long(e.toString()))
                .collect(Collectors.toList());
        Promise<PhResult> promise = Promise.promise();
        groupService.createGroup(groupName, createUserId, memberList, promise);
        promise.future()
                .onFailure(e->{
                    logger.error(e);
                    badResult(context, e);
                })
                .onSuccess(result->{
                    okResult(context, result);
                });
    }

    public void getGroupList(RoutingContext context) {
        String contentType = context.request().getHeader("Content-Type");
        if (StringUtils.isNotBlank(contentType) && contentType.contains("application/octet-stream")) {
            JsonObject body = context.getBodyAsJson();
            String userId = body.getString("user_id");
            // 查询用户联系人列表
            Promise<List<JsonObject>> promise = Promise.promise();
            groupService.getGroupList(Long.parseLong(userId), promise);
            promise.future()
                    .onSuccess(list->{
                        JsonArray jsonArray = new JsonArray(list);
                        okResult(context, "OK", JsonUtil.toStrVal(jsonArray).toString());
                    })
                    .onFailure(e->{
                        badResult(context, e);
                    });

        } else {
            logger.info("查询用户列表，请求数据格式错误");
            badResult(context, new Exception("查询用户列表，请求数据格式错误"));
        }


    }

    public void applyJoinGroup(RoutingContext context) {
        JsonObject body = context.get("ext");
        Promise<PhResult> promise = Promise.promise();
        groupService.applyJoinGroup(
                body.getLong("groupId"),
                body.getLong("applyUserId"),
                body.getLong("recommendUserId"),
                body.getString("comment"),
                promise
        );
        promise.future()
                .onFailure(e->badResult(context,e))
                .onSuccess(result->{
                    okResult(context, result);
                });

    }

    public void addGroupMember(RoutingContext context) {
        JsonObject body = context.get("ext");
        Promise<PhResult> promise = Promise.promise();
        groupService.addGroupMember(
                JsonUtil.getLong(body, "groupId"),
                JsonUtil.getLong(body, "userId"),
                JsonUtil.getString(body, "comment"),
                promise
        );
        promise.future()
                .onFailure(e->badResult(context, e))
                .onSuccess(result->okResult(context, result));
    }

    public void approvedApply(RoutingContext context) {
        JsonObject body = context.get("ext");
        Promise<PhResult> promise = Promise.promise();
        groupService.approvedApply(
                body.getLong("applyId"),
                body.getInteger("feedStatus"),
                body.getString("feedComment"),
                promise
        );
        promise.future()
                .onFailure(e->badResult(context, e))
                .onSuccess(result->okResult(context, result));
    }

    public void getApplyList(RoutingContext context) {
        String strGroupId = context.pathParam("groupId");
        long groupId = Long.parseLong(strGroupId);
        Promise<List<JsonObject>> promise = Promise.promise();
        groupService.getApplyList(groupId, promise);
        promise.future()
                .onFailure(e->badResult(context, e))
                .onSuccess(list->{
                    okResult(context, "OK", JsonUtil.toStrVal(new JsonArray(list)).toString());
                });
    }

    public void getGroupMemberList(RoutingContext context) {
        JsonObject body = context.get("ext");
        Long groupId = Long.parseLong(body.getString("group_id"));
        Promise<List<JsonObject>> promise = Promise.promise();
        groupService.getMemberList(groupId, promise);
        promise.future()
                .onFailure(e->badResult(context, e))
                .onSuccess(list->{
                    okResult(context, "OK", JsonUtil.toStrVal(new JsonArray(list)).toString());
                });
    }
}
